package com.example.finaltest.goods;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.finaltest.R;
import com.example.finaltest.login.UserBean;
import com.example.finaltest.utils.BaseActivity;
import com.example.finaltest.utils.EditUserDialog;
import com.example.finaltest.utils.SaveUserUtils;
import com.example.finaltest.utils.URLUtils;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.example.finaltest.utils.URLUtils.insertBought_url;
import static java.lang.Math.min;

public class Payment1Activity extends BaseActivity implements Callback.CommonCallback<String> {
    ImageView back,goods_picture;
    LinearLayout l1;
    TextView add_ad,add_info,goods_info,goods_price,goods_count,bottom_tv1,goods_sum;
    int num;
    int flg;
    Button btn1,btn_1,btn_2,btn_3;
    UserBean.DataBean userInfo, newInfo;
    GoodsBean.DataBean dataBean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment1);
        userInfo = SaveUserUtils.getUserInfo(this); //获取到保存的登录信息
        newInfo = new UserBean.DataBean(userInfo.getId(),userInfo.getPhone(),userInfo.getPassword(),
                userInfo.getName(),userInfo.getAddress(),userInfo.getNickname(),userInfo.getQuestion(), userInfo.getAnswer());

        dataBean = (GoodsBean.DataBean)getIntent().getSerializableExtra("goods");
        Log.i("ooo", "onItemClick:databean== "+dataBean.toString());
        num =  getIntent().getIntExtra("num",0);
        Log.i("ooo", "onItemClick:num== "+num);
        flg=0;
        initView();
        setListener();
        setView();
    }
    private void setView() {
        if(userInfo.getAddress()!="")
            add_ad.setText(userInfo.getAddress());

        String phone=userInfo.getPhone()+"";
        add_info.setText(userInfo.getName()+" "+phone.substring(0,3)+"****"+phone.substring(7));
        goods_info.setText(dataBean.getInfo());
        goods_price.setText("单价"+"￥"+dataBean.getPrice()+"");
        goods_count.setText("数量："+num+"");
        goods_sum.setText("合计： ￥"+num*dataBean.getPrice()+"");
        goods_info.setText(dataBean.getInfo().substring(0,min(15,dataBean.getInfo().length()))+"....");

        String photo = dataBean.getPhoto();
        if (!TextUtils.isEmpty(photo)) {
            String photourl = URLUtils.PUBLIC_URL+photo;
            Picasso.with(this).load(photourl).into(goods_picture);
        }
        bottom_tv1.setText("￥"+num*dataBean.getPrice()+"");
    }

    private void setListener() {
        l1.setOnClickListener(listener);
        btn1.setOnClickListener(listener);
        back.setOnClickListener(listener);
        btn_1.setOnClickListener(listener);
        btn_2.setOnClickListener(listener);
        btn_3.setOnClickListener(listener);
    }

    private void initView() {
        l1 = findViewById(R.id.layout1);
        btn1 = findViewById(R.id.pay_ensure);
        back = findViewById(R.id.pay_back);
        add_ad= findViewById(R.id.pay_add_tv3);
        add_info=findViewById(R.id.pay_add_tv4);
        goods_sum=findViewById(R.id.fees);
        goods_info= findViewById(R.id.pay_goods_tv2);
        goods_price= findViewById(R.id.pay_goods_tv3);
        goods_count = findViewById(R.id.pay_goods_tv4);
        goods_picture= findViewById(R.id.pay_goods_picture);
        bottom_tv1= findViewById(R.id.ensure_price);
        btn_1=findViewById(R.id.pay_wechat);
        btn_2=findViewById(R.id.pay_card);
        btn_3=findViewById(R.id.pay_alipay);
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int vid = v.getId();  // 获取到被点击的id
            switch (vid) {
                case R.id.layout1://修改地址并保存
                    String hint ="请输入修改的地址信息:";
                    showEditUserDialog(hint,add_ad);
                    break;
                case R.id.pay_back:
                    finish();
                    break;
                case R.id.pay_ensure:
                    if(flg==0){
                        Toast.makeText(Payment1Activity.this, "请先选择支付方式！", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        postNetwork1();
                    }
                    break;
                case R.id.pay_wechat: case R.id.pay_card: case R.id.pay_alipay:
                    flg++;
                    break;

            }
        }
    };

    private void postNetwork1() {

        Map<String, String> map = new HashMap<>();
        map.put("userId", userInfo.getId() + "");
        map.put("count",num+"");
        map.put("commodityId",dataBean.getId()+"");
        postNetwork(insertBought_url, map);
    }

    public void onSuccess(String result) {
        UserBean jsonbean = new Gson().fromJson(result, UserBean.class);
        if (jsonbean.getCode() == 200) {
            Toast.makeText(Payment1Activity.this, "购买成功！", Toast.LENGTH_SHORT).show();
//            Intent intent = new Intent(Payment1Activity.this, GoodsDetailsActivity.class);
//            startActivity(intent);
            finish();
        } else {
            Toast.makeText(Payment1Activity.this, "购买失败！", Toast.LENGTH_SHORT).show();
        }

    }

    private void showEditUserDialog(String hint,TextView tv) {
//        1.创建对话框对象
        EditUserDialog dialog = new EditUserDialog(this);
//        2.显示对话框
        dialog.show();
//        3.设置参数
        dialog.setDialogWidth();
        dialog.setTipHint(hint);
        dialog.setOnEnsureListener(new EditUserDialog.OnEnsureListener() {
            @Override
            public void onEnsure(String msg) {
                tv.setText(msg);
                newInfo.setAddress(msg);
                Map<String, String> map = new HashMap<>();
                map.put("id", newInfo.getId() + "");
                map.put("address",newInfo.getAddress());
                map.put("nickname",newInfo.getNickname());
                map.put("name", newInfo.getName());
                postNetwork2(URLUtils.updateinfo_url, map);
                dialog.cancel();
            }
        });

    }

    private void postNetwork2(String url, Map<String, String> map) {
        RequestParams params = new RequestParams(url);
//        将提交的键值对放到请求参数当中
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            String val = map.get(key);
            params.addParameter(key, val);
        }
        params.setAsJsonContent(true);
        params.setBodyContentType("application/json;charset=utf-8");
        x.http().post(params, new CommonCallback<String>() {
            private String TAG = "mjw123";

            @Override
            public void onSuccess(String result) {
                Log.i(TAG, "onSuccess: result==" + result);
                UserBean jsonbean = new Gson().fromJson(result, UserBean.class);
                switch (jsonbean.getCode()) {
                    case 200:
                        SaveUserUtils.saveUserToFile(Payment1Activity.this, newInfo);
                        userInfo = SaveUserUtils.getUserInfo(Payment1Activity.this);
                        Toast.makeText(Payment1Activity.this, "地址修改成功！", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(Payment1Activity.this, "地址修改失败！", Toast.LENGTH_SHORT).show();
                        break;

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError: ex==" + ex.getMessage());

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
